<?php
namespace app\api\service;
use think\Controller;
use Des3\DES3;
use think\Db;
use think\Session;

class Member extends Controller {
    static protected $err_code = 0;
    // 登录接口
    static public function login($param) {
        //return ['data' => $param, 'code' => 1, 'msg' => 'FAULT'];
        if(!isset($param['phone']) || !isset($param['type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        try{
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $type = $param['type'];
            if(empty($phone)) {
                self::$err_code = 400020;
                throw new \Exception('FAULT');
            }
            switch ($type) {
                case 1:
                    $pwd = isset($param['password']) ? $param['password'] : '';
                    $password = $des->decrypt($pwd);
                    if (empty($password)) {
                        self::$err_code = 400021;
                        throw new \Exception('FAULT');
                    }
                    /* 获取密码 */
                    $password = md5(md5($password) . md5($phone));
                    $member = Db::table('mob_member')->where('phone', $phone)->where('password', $password)->find();
                    break;
                case 2:
                    $code = isset($param['code']) ? $param['code'] : 0;
                    if (empty($code)){
                        self::$err_code = 400068;
                        throw new \Exception('FAULT');
                    }
                    // 验证短信验证码是否有效
                    $check_code = check_note_code($code, $phone, 1);
                    if($check_code['code'] != 200) {
                        self::$err_code = $check_code['code'];
                        throw new \Exception('FAULT');
                    }
                    $member = Db::table('mob_member')->where('phone', $phone)->find();
                    if (!$member) {
                        // 验证码登录   用户不存在时   自动注册
                        $register_data = [
                            'phone' => $des->encrypt($phone),
                            'password' => $des->encrypt('mobom' . rand(1000, 9999)),
                            'code' => 'adkhdaskjdlfadsljiodfwr98273423423'
                        ];
                        $register = self::register($register_data);
                        if ($register['code'] != 200) {
                            self::$err_code = $register['code'];
                            throw new \Exception($register['msg']);
                        }
                    }
                    break;
                default :
                    self::$err_code = 400069;
                    throw new \Exception('FAULT');
                    break;
            }
            if (!$member) {
                self::$err_code = 400022;
                throw new \Exception('FAULT');
            }
            $data['member_id'] = $member['id'];
            $data['phone'] = $phone;
            $data['set_pay_password'] = $member['safe_password'] > 0 ? 1 : 0;

            $data['repair'] = Db::table('mob_repair')->field('audit_status, msg')->where('member_id', $member['id'])->find();
            $data['dealer'] = Db::table('mob_dealer')->field('audit_status, msg')->where('member_id', $member['id'])->find();
            $data['partner'] = Db::table('mob_partner')->field('audit_status, msg')->where('member_id', $member['id'])->find();

            $member_role_info = Db::table('mob_member_role_info')->where('member_id', $member['id'])->where('type', 0)->find();
            $repair_role_info = Db::table('mob_member_role_info')->where('member_id', $member['id'])->where('type', 1)->find();
            $dealer_role_info = Db::table('mob_member_role_info')->where('member_id', $member['id'])->where('type', 2)->find();
            $partner_role_info = Db::table('mob_member_role_info')->where('member_id', $member['id'])->where('type', 3)->find();

            $data['member_role_info'] = $member_role_info;
            $data['repair_role_info'] = $repair_role_info;
            $data['dealer_role_info'] = $dealer_role_info;
            $data['partner_role_info'] = $partner_role_info;

            Db::table('mob_member')->where('id', $member['id'])->update(['last_login_time' => time(), 'last_login_ip' => input('get.member_ip')]);
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => $data];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 注册接口
    static public function register($param) {

        if(!isset($param['phone']) ||
            !isset($param['password']) || !isset($param['code'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        // 启动事务
        Db::startTrans();
        try{
            /*调用验证器 验证数据*/
            $validate = validate('Member');

            // 解密数据
            $des = new DES3();
            $param['phone'] = $des->decrypt($param['phone']);
            $param['password'] = $des->decrypt($param['password']);
            if(!$validate->scene('add')->check($param)){
                self::$err_code = $validate->getError();
                throw new \Exception('FAULT1');
            }

            if ($param['code'] != 'adkhdaskjdlfadsljiodfwr98273423423') {   // 如果是从登录接口过来的  不检查验证码
                // 验证短信验证码是否有效
                $check_code = check_note_code($param['code'], $param['phone'], 1);
                if($check_code['code'] != 200) {
                    self::$err_code = $check_code['code'];
                    throw new \Exception($check_code['msg']);
                }
            }

            // 组装注册用户数据
            $data['phone']  = $param['phone'];
            $data['password']  = md5(md5($param['password']) . md5($param['phone']));

            if(isset($param['parent_phone']) && !empty($param['parent_phone'])) {
                $parent_phone = $des->decrypt($param['parent_phone']);
                // 获取上级市场线
                $parent_info = get_parents($parent_phone);
                if (!$parent_info) {
                    self::$err_code = 400134;
                    throw new \Exception($check_code['msg']);
                }
                $data['parents']  = $parent_info['parents'];
                $data['parent_id']  = $parent_info['id'];
            }
            //return ['data' => $data, 'code' => 1, 'msg' => 'FAULT'];
            //return $data;
            $rs = Db::table('mob_member')->insertGetId($data);

            // 创建一条基本信息记录
            $member_role_infos = [
                [ 'member_id' => $rs, 'type' => 0 ],
                [ 'member_id' => $rs, 'type' => 1 ],
                [ 'member_id' => $rs, 'type' => 2 ],
                [ 'member_id' => $rs, 'type' => 3 ]
            ];
            Db::table('mob_member_role_info')->insertAll($member_role_infos);

            Db::commit();

            return ['data' => ['member_id' => $rs], 'code' => 200,'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }
    }

    // 找回密码
    static public function retrieve_password($param) {
        if(!isset($param['phone']) || !isset($param['password']) || !isset($param['code']))
            return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        // 启动事务
        Db::startTrans();
        try{
            // 解密数据
            $des = new DES3();
            $param['phone'] = $des->decrypt($param['phone']);
            $param['password'] = $des->decrypt($param['password']);
            /*调用验证器 验证数据*/
            $validate = validate('Member');
            //dump($param);
            if(!$validate->scene('retrieve_password')->check($param)){
                $error_code = $validate->getError();
                self::$err_code = $error_code;
                throw new \Exception('FAULT123');
            }
            //dump($param);
            // 检查帐号是否存在
            $member = Db::table('mob_member')->where('phone', $param['phone'])->find();
            //dump($member);
            if (!$member) {
                self::$err_code = 400029;
                throw new \Exception('FAULT');
            }

            // 验证短信验证码是否有效
            $check_code = check_note_code($param['code'], $param['phone'], 1);
            if($check_code['code'] != 200) {
                self::$err_code = $check_code['code'];
                throw new \Exception($check_code['msg']);
            }
            
            // 加密用户密码
            $data['password']  = md5(md5($param['password']) . md5($param['phone']));

            // 写入数据库
            Db::table('mob_member')->where('phone', $param['phone'])->update($data);

            Db::commit();
            return ['data' => '', 'code' => 200,'msg' => 'SUCCESS'];

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['data'=>'', 'code'=>self::$err_code, 'msg'=> $e->getMessage()];
        }

    }

    // 获取用户列表
    static public function get_member_list($param) {
        try{
            $where = [];
            //return ['data' => $param, 'code' => 1, 'msg' => 'FAULT'];
            if(isset($param['status'])) {
                $where['status'] = $param['status'];
            }
            $list = Db::table('mob_member')->where($where)->select();
            return ['data' => $list, 'code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['data'=>'', 'code'=>0, 'msg'=> $e->getMessage()];
        }
    }

    // 修改手机号码
    static public function update_phone($param) {
        if(!isset($param['member_id']) ||
            !isset($param['phone']) || !isset($param['code']) ) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];


        // 启动事务
        Db::startTrans();
        try{
            $id = $param['member_id'];

            // 检查用户三个月之内是否有修改过手机
            $check_time = strtotime(date('Y-m-d')) - 60 * 60 * 24 * 90;
            $member = Db::table('mob_member_update_phone_log')->where('member_id', $id)->whereTime('add_time', '>', $check_time)->find();
            if ($member) {
                self::$err_code = 400130;
                throw new \Exception('FAULT');
            }

            $old_phone = Db::table('mob_member')->where('id', $id)->value('phone');

            $des = new DES3();
            $phone = $des->decrypt($param['phone']);

            /*调用验证器 验证数据*/
            $validate = validate('Member');
            if(!$validate->scene('update_phone')->check(['phone' => $phone])){
                self::$err_code = $validate->getError();
                throw new \Exception('FAULT');
            }

            // 验证短信验证码是否有效
            $check_code = check_note_code($param['code'], $phone, 1);
            if($check_code['code'] != 200) {
                self::$err_code = $check_code['code'];
                throw new \Exception($check_code['msg']);
            }

            // 修改手机号码，并且解除绑定
            Db::table('mob_member')->where('id', $id)->update(['phone' => $phone, 'openid' => '', 'band_status' => 2]);

            // 添加手机修改记录
            $data = [
                'member_id' => $param['member_id'],
                'old_phone' => $old_phone,
                'phone' => $phone,
                'add_time' => strtotime(date('Y-m-d'))
            ];
            Db::table('mob_member_update_phone_log')->insert($data);

            Db::commit();
            Session::clear();;  // 修改成功  清空SESSION
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 设置安全密码
    static public function save_safe_password($param) {
        if(!isset($param['member_id']) ||
            !isset($param['safe_password'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        // 启动事务
        Db::startTrans();
        try{
            $id = $param['member_id'];
            //$phone = Db::table('mob_member')->where('id', $id)->value('phone');

//            // 验证短信验证码是否有效
//            $check_code = check_note_code($param['code'], $phone, 1);
//            if($check_code['code'] != 200) {
//                self::$err_code = $check_code['code'];
//                throw new \Exception($check_code['msg']);
//            }

            $des = new DES3();
            $safe_password = $des->decrypt($param['safe_password']);
            /*调用验证器 验证数据*/
            $validate = validate('Member');
            if(!$validate->scene('safe_password')->check(['safe_password' => $safe_password])){
                self::$err_code = $validate->getError();
                throw new \Exception($validate->getError());
            }
            $safe_password = md5($safe_password);
            Db::table('mob_member')->where('id', $id)->update(['safe_password' => $safe_password]);

            // 设置成功   清除错误记录（解锁）
            db('safe_password_error_log')->where('member_id', $param['member_id'])->delete();
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 修改登录密码
    static public function update_password($param) {
        if(!isset($param['member_id']) ||
            !isset($param['password']) || !isset($param['new_password']) || !isset($param['re_new_password'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            if ($param['new_password'] != $param['re_new_password']) {
                self::$err_code = 400125; // 两次新密码不一致
                throw new \Exception('FAULT');
            }

            $id = $param['member_id'];

            $des = new DES3();
            $password = $des->decrypt($param['password']);

            $member = Db::table('mob_member')->field('phone, password')->where('id', $id)->find();
            if ($member['password'] != md5(md5($password) . md5($member['phone']))) {
                self::$err_code = 400124; // 原密码不匹配
                throw new \Exception('FAULT');
            }

            $new_password = $des->decrypt($param['new_password']);
            /*调用验证器 验证数据*/
            $validate = validate('Member');
            if(!$validate->scene('password')->check(['password' => $new_password])){
                self::$err_code = $validate->getError();
                throw new \Exception($validate->getError());
            }
            /* 获取密码 */
            $password = md5(md5($new_password) . md5($member['phone']));
            Db::table('mob_member')->where('id', $id)->update(['password' => $password, 'openid' => '', 'band_status' => 2]);
            Db::commit();
            Session::clear();;  // 修改成功  清空SESSION
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code ,'msg'=> $e->getMessage()];
        }
    }

    // 修改基本信息
    static public function save_role_info($param) {
        if(!isset($param['member_id']) || !isset($param['field']) || !isset($param['value']) ||
            !isset($param['type'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];

        // 启动事务
        Db::startTrans();
        try{
            $map['member_id'] = $param['member_id'];
            $map['type'] = $param['type'];
            if ($param['field'] == 'birthday') {
                $param['value'] = strtotime($param['value']);
            }
            if ($param['field'] == 'phone') {
                /*调用验证器 验证数据*/
                $validate = validate('Member');
                if(!$validate->scene('phone')->check(['phone' => $param['value']])){
                    self::$err_code = $validate->getError();
                    throw new \Exception($validate->getError());
                }
            }
            $data[$param['field']] = $param['value'];
            $member_role_info = Db::table('mob_member_role_info')->where($map)->find();
            if (!$member_role_info) {
                $map[$param['field']] = $param['value'];
                Db::table('mob_member_role_info')->insert($map);
            } else {
                Db::table('mob_member_role_info')->where($map)->update($data);
            }
            Db::commit();
            return ['code' => 200, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 获取上级用户姓名
    static public function get_referrer($param) {
        if(!isset($param['phone'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
//            $get_referrer_error_num = cookie('get_referrer_error') ? cookie('get_referrer_error') : 0;
//            if ($get_referrer_error_num >= 3) {
//                self::$err_code = 400129; // 连续错误输入三次推荐人
//                throw new \Exception('FAULT');
//            }
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $member = db('member')->field('id, proposer')->where('phone', $phone)->find();
            if (!$member['id']) {
                // 用户不存在  记录错误次数
//                $error_num = $get_referrer_error_num+1;
//                $cookie_time = $error_num >=3 ? 300 : strtotime(date("Y-m-d",strtotime("+1 day"))) - time();
//                cookie('get_referrer_error', $error_num, $cookie_time);
                self::$err_code = 400134;
                throw new \Exception('FAULT');
            }
            //cookie('get_referrer_error', null);
            if (!$member['proposer']) {
                $member['proposer'] = $phone;
            }
            return ['code' => 200, 'data' => $member, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 检查帐号是否存在
    static public function check_phone($param) {
        if(!isset($param['phone'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try{
            $des = new DES3();
            $phone = $des->decrypt($param['phone']);
            $member = db('member')->field('id')->where('phone', $phone)->find();
            return ['code' => 200, 'data' => $member, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }

    // 获取用户端个人中心首页数据
    static public function get_member_index($param) {
        if(!isset($param['member_id']) || !isset($param['terrace'])) return ['data'=>'','code'=>400001,'msg'=> 'FAULT'];
        try {
            $map['m.id'] = $param['member_id'];
            if (isset($param['action']) && $param['action'] == 'weixin') {
                $map['m.openid'] = session('openid');
                $map['m.band_status'] = 1;
            }

            $member_info = db('member')->alias('m')->field('m.id, m.point, m.money, mr.nickname, mr.headimgurl')
                ->join("mob_member_role_info mr", "m.id = mr.member_id and mr.type = 0", 'LEFT')->where($map)->find();

            // 获取可用优惠券数量
            $coupon_where['member_id'] = $member_info['id'];
            $coupon_where['status'] = 0;
            $coupon_where['use_time'] = ['lt', time()];
            $coupon_where['overdue_time'] = ['gt', time()];
            $member_info['coupon_count'] = db('member_coupon')->where($coupon_where)->count();

            // 获取首页订单统计数据
            $orders = db('order_server')->field('status, member_id, replytime, after_sale_status, order_receiving_time, is_comment')
                ->where('member_id', $param['member_id'])
                ->where('after_sale_status', 0)
                ->select();

            //初始化 待抢单、 议价中、 待付款、 服务中、 待确认 统计数量
            $dqd = $yj = $dfk = $fwz = $dqr = $dpj = 0;
            foreach ($orders as $o) {
                switch ($o['status']) {
                    case 1:
                        $dqd++;
                        break;
                    case 2:
                        $dfk++;
                        break;
                    case 3:
                        $fwz++;
                        break;
                    case 4:
                        $dqr++;
                        break;
                    case 6:
                        if ($o['is_comment'] == 0 && $o['after_sale_status'] == 0) {
                            $dpj++;
                        }
                        break;
                    case 11:
                        $yj++;
                        break;
                }
            }
            $order_num = [
                'dqd' => $dqd,
                'yj' => $yj,
                'dfk' => $dfk,
                'fwz' => $fwz,
                'dqr' => $dqr,
                'dpj' => $dpj,
            ];
            $member_info['order_num'] = $order_num;

            // 获取售后订单统计
            $austin_num = db('order_austin')->where('member_id', $param['member_id'])->where('status', 0)->count();
            $member_info['austin_num'] = $austin_num;

            // 获取申诉订单统计
            $complaint_num = db('order_austin')->where('member_id', $param['member_id'])->where('status', 4)->count();
            $member_info['complaint_num'] = $complaint_num;

            // 获取我的默认爱车
            $my_car = db('my_car')->where('member_id', $param['member_id'])->order('is_default desc')->find();
            $member_info['my_car'] = $my_car['name'];

            // 是否签到
            $registration = Registration::check_registration(['member_id'=> $param['member_id']]);
            //dump($registration);
            $member_info['is_registration'] = ($registration['code'] == 200 ? 0 :1); // 200 标识检查接口走完，意味着还没有签到

            // 是否有新消息
            $msg_where = [
                'member_role' => 'member',
                'member_id' => $param['member_id'],
                'terrace' => $param['terrace'],
                'status' => 0
            ];
            $member_info['new_msg_num'] = Db::table('mob_member_message')->where($msg_where)->count();

            return ['code' => 200, 'data' => $member_info, 'msg' => 'SUCCESS'];
        } catch (\Exception $e) {
            return ['code'=>self::$err_code,'msg'=> $e->getMessage()];
        }
    }
}
